package com.jt.blog.server.impl;

import com.jt.blog.dao.TagMapper;
import com.jt.blog.domain.Tag;
import com.jt.blog.server.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagServicelmpl implements TagService {

    @Autowired
    private RedisTemplate redisTemplate;
    //private RedisTemplate<String, List<Tag>> redisTemplate;
    //private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private TagMapper tagMapper;

    @Override
    public List<Tag> selectTags(){

        //Long before = System.currentTimeMillis();

        //1.从redis查询Tag信息，redis有则直接返回
        ValueOperations<String, List<Tag>> valueOperations =
                redisTemplate.opsForValue();

//        ValueOperations<Object, Object> valueOperations =
//                redisTemplate.opsForValue();

        List<Tag> tags = valueOperations.get("tags");
       // List<Tag> tags = (List<Tag>) valueOperations.get("tags");
        //System.out.println("tags="+tags);

       // Long after = System.currentTimeMillis();
       // System.out.println("mysql.time="+(after-before));

        if (tags != null && tags.isEmpty()) return tags;

        //2.从redis没有获取tag信息，查询mysql
        //System.out.println(" == select Tags from mysql == ");
        //List<Tag> dbTags = tagMapper.selectList(null);
         tags = tagMapper.selectList(null);

        //3.将从mysql查询到tag信息存储到redis
        //valueOperations.set("tags", dbTags);
        valueOperations.set("tags", tags);

        //4.返回查询结果
        //return dbTags;
       // after = System.currentTimeMillis();
       // System.out.println("mysql.time="+(after-before));
        return tags;
    }

}
